package com.example.administrator.fastdream.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.administrator.fastdream.R;
import com.example.administrator.fastdream.date.bean.ChooseMoneyBean;
import com.example.administrator.fastdream.date.bean.JoinBean;
import com.example.administrator.fastdream.date.bean.LuckyBean;
import com.example.administrator.fastdream.date.bean.MainBean;
import com.example.administrator.fastdream.date.bean.OpenRedBean;
import com.example.administrator.fastdream.date.presenter.JoinPresenter;
import com.example.administrator.fastdream.date.presenter.LuckyPresenter;
import com.example.administrator.fastdream.date.presenter.MainPresenter;
import com.example.administrator.fastdream.date.presenter.OpenRedPresenter;
import com.example.administrator.fastdream.date.utils.CacheUtils;
import com.example.administrator.fastdream.date.utils.DimenUtil;
import com.example.administrator.fastdream.date.utils.EventBusCode;
import com.example.administrator.fastdream.date.utils.LoginHelper;
import com.example.administrator.fastdream.date.utils.MyUtils;
import com.example.administrator.fastdream.view.base.BaseActivity;
import com.example.administrator.fastdream.view.base.BaseDialog;
import com.example.administrator.fastdream.view.view.CustomCircleProgressBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends BaseActivity implements LuckyPresenter.DataCallBack, MainPresenter.DataCallBack, JoinPresenter.DataCallBack, OpenRedPresenter.DataCallBack {

    @BindView(R.id.iv_mine)
    ImageView ivMine;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_gongao)
    TextView tvGongao;
    @BindView(R.id.myProgress)
    CustomCircleProgressBar myProgress;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_join)
    TextView tvJoin;
    @BindView(R.id.tv_join_count)
    TextView tvJoinCount;
    @BindView(R.id.tv_perfect_info)
    TextView tvPerfectInfo;
    @BindView(R.id.tv_share_dream)
    TextView tvShareDream;
    @BindView(R.id.tv_myrecord)
    TextView tvMyrecord;
    @BindView(R.id.view_record_point)
    View viewRecordPoint;
    @BindView(R.id.tv_lookall)
    TextView tvLookall;
    @BindView(R.id.iv3)
    ImageView iv3;
    @BindView(R.id.tv_look_problem)
    TextView tvLookProblem;
    @BindView(R.id.iv_weixin)
    ImageView ivWeixin;
    @BindView(R.id.iv_friendcirlce)
    ImageView ivFriendcirlce;
    @BindView(R.id.iv_qq)
    ImageView ivQq;
    @BindView(R.id.iv_qq_zone)
    ImageView ivQqZone;
    private BaseDialog mDialog;
    private BaseDialog.Builder mBuilder;
    private long preTime;
    private List<ChooseMoneyBean> luckyList;
    private LuckyNumberAdapter luckyNumberAdapter;
    private LuckyPresenter presenter;
    private MainPresenter MainPresenter;

    private OpenRedPresenter openRedPresenter;
    private JoinPresenter JoinPresenter;
    private String unit_price;
    private String Issue;
    private String lucky_number;
    private boolean isJoin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        ivMine.setVisibility(View.VISIBLE);
        myProgress.setMaxProgress(0);
        myProgress.setProgress(0);
        myProgress.setProgressText("0/0");
        presenter = new LuckyPresenter(this, this);
        MainPresenter = new MainPresenter(this, this);
        JoinPresenter = new JoinPresenter(this, this);
        openRedPresenter = new OpenRedPresenter(this, this);
        if (TextUtils.isEmpty((String) CacheUtils.get("token"))) {
            MainPresenter.data("2", "0");
        } else {
            MainPresenter.data("1", (String) CacheUtils.get("token"));
            JPushInterface.setAliasAndTags(MainActivity.this, (String) CacheUtils.get("id"), null, null);
        }
        if (CacheUtils.get("isSetDream") == null) {
            showPerfectDreamDialog();
            CacheUtils.put("isSetDream", true);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (TextUtils.isEmpty((String) CacheUtils.get("token"))) {
            MainPresenter.data("2", "0");
        } else {
            MainPresenter.data("1", (String) CacheUtils.get("token"));
        }
    }

    private void showOpenRedBaoDialog() {
        mBuilder = new BaseDialog.Builder(this);
        int dialog_width = MyUtils.getScreenWidth(this) - DimenUtil.dp2px(this, 40);
        int dialog_height = (int) (dialog_width / 0.87f);
        mDialog = mBuilder.setViewId(R.layout.dialog_openhongbao)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, dialog_height)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        mDialog.getView(R.id.view_open).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                openRedPresenter.data((String) CacheUtils.get("token"), (Integer.valueOf(Issue) - 1) + "");
            }
        });
        mDialog.getView(R.id.tv_detail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mDialog.dismiss();
            }
        });
    }

    private void showZhongJiangReslutDialog(String yuan) {
        mBuilder = new BaseDialog.Builder(this);
        int dialog_width = MyUtils.getScreenWidth(this) - DimenUtil.dp2px(this, 40);
        int dialog_height = (int) (dialog_width / 0.87f);
        mDialog = mBuilder.setViewId(R.layout.dialog_zhongjiang_result)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, dialog_height)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        ((TextView) mDialog.getView(R.id.tv_yuan)).setText(yuan + "元");
        mDialog.getView(R.id.tv_yes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    private void showZhongJiangYuanMengDialog(String yuan) {
        mBuilder = new BaseDialog.Builder(this);
        int dialog_width = MyUtils.getScreenWidth(this) - DimenUtil.dp2px(this, 40);
        int dialog_height = (int) (dialog_width / 0.87f);
        mDialog = mBuilder.setViewId(R.layout.dialog_zhongjiang_yuanmeng)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, dialog_height)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        ((TextView) mDialog.getView(R.id.tv_yuan)).setText(yuan + "元");
        mDialog.getView(R.id.tv_yes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    private void showMeiZhongJiangDialog() {
        mBuilder = new BaseDialog.Builder(this);
        int dialog_width = MyUtils.getScreenWidth(this) - DimenUtil.dp2px(this, 40);
        int dialog_height = (int) (dialog_width / 0.87f);
        mDialog = mBuilder.setViewId(R.layout.dialog_meizhongjiang)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, dialog_height)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        mDialog.getView(R.id.view_zhidaole).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mDialog.dismiss();
            }
        });
    }

    private void showJoinSuccessmDialog(String tv_money) {
        mBuilder = new BaseDialog.Builder(this);
        int dialog_width = MyUtils.getScreenWidth(this) - DimenUtil.dp2px(this, 40);
        int dialog_height = (int) (dialog_width / 0.9f);
        mDialog = mBuilder.setViewId(R.layout.dialog_join_success)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, dialog_height)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        ((TextView) mDialog.getView(R.id.Text_Issue)).setText(Issue.substring(2, Issue.length()) + "期");
        ((TextView) mDialog.getView(R.id.tv_money)).setText(tv_money);
        mDialog.getView(R.id.iv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.getView(R.id.tv_yes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    private void showPerfectDreamDialog() {
        mBuilder = new BaseDialog.Builder(this);
        mDialog = mBuilder.setViewId(R.layout.dialog_perfect_dream)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        mDialog.getView(R.id.iv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.getView(R.id.tv_yes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginHelper.login(MainActivity.this, new LoginHelper.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        startActivity(new Intent(mContext, MyDreamActivity.class));
                        mDialog.dismiss();
                    }
                });
            }
        });
    }

    private void showChooseLuckyNumberDialog(final LuckyBean dataBean) {
        mBuilder = new BaseDialog.Builder(this);
        mDialog = mBuilder.setViewId(R.layout.dialog_chooseluckynumber)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        mDialog.getView(R.id.iv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        final TextView tv_yes = mDialog.getView(R.id.tv_yes);
        tv_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isChooseLuckyNumber()) {
                    Toast.makeText(mContext, "请选择本期幸运数字", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(mContext, JoinActivity.class);
                intent.putExtra("issue", Issue);
                intent.putExtra("lucky_number", lucky_number);
                intent.putExtra("unit_price", unit_price);
                startActivityForResult(intent, 1);
                mDialog.dismiss();
            }
        });
        RecyclerView recyclerView = mDialog.getView(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        luckyList = new ArrayList<>();
        luckyList.add(new ChooseMoneyBean(R.drawable.one, "1万元", dataBean.getData().getOne()));
        luckyList.add(new ChooseMoneyBean(R.drawable.two, "5万元", dataBean.getData().getTwo()));
        luckyList.add(new ChooseMoneyBean(R.drawable.three, "15万元", dataBean.getData().getThree()));
        luckyList.add(new ChooseMoneyBean(R.drawable.four, "20万元", dataBean.getData().getFour()));
        luckyNumberAdapter = new LuckyNumberAdapter(R.layout.item_choose_luckynumber, luckyList);
        recyclerView.setAdapter(luckyNumberAdapter);
        luckyNumberAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < luckyList.size(); i++) {
                    if (i == position) {
                        luckyList.get(position).setChecked(!luckyList.get(position).isChecked());
                    } else {
                        luckyList.get(i).setChecked(false);//注意这里是i
                    }
                }
                luckyNumberAdapter.notifyDataSetChanged();
                if (!isChooseLuckyNumber()) {
                    tv_yes.setBackgroundResource(R.drawable.shape_button_unchecked);
                } else {
                    tv_yes.setBackgroundResource(R.drawable.shape_button_checked);
                }
            }
        });

    }

    private boolean isChooseLuckyNumber() {
        for (int i = 0; i < luckyList.size(); i++) {
            if (luckyList.get(i).isChecked()) {
                lucky_number = (i + 1) + "";
                return true;
            }
        }
        return false;
    }

    @Override
    public void date(LuckyBean dataBean) {
        showChooseLuckyNumberDialog(dataBean);
    }

    @Override
    public void date(MainBean dataBean) {
        Issue = dataBean.getData().getLottery_info().getIssue();
        unit_price = dataBean.getData().getLottery_info().getUnit_price();
        tvTitle.setText(dataBean.getData().getLottery_info().getIssue().substring(2, dataBean.getData().getLottery_info().getIssue().length()) + "期");
        tvTime.setText("开奖时间预计：" + dataBean.getData().getLottery_info().getExpected_opening_time());
        tvJoinCount.setText("已参加" + dataBean.getData().getLottery_info().getAlready_participated_count() + "人");
        myProgress.setMaxProgress(Integer.valueOf(dataBean.getData().getLottery_info().getTotal_price()));
        myProgress.setProgress(Integer.valueOf(dataBean.getData().getLottery_info().getCurrent_quota()));
        myProgress.setProgressText(dataBean.getData().getLottery_info().getCurrent_quota() + "/" + dataBean.getData().getLottery_info().getTotal_price());
        if (dataBean.getData().getUser_lst() != null && dataBean.getData().getUser_lst().size() > 0) {
            for (int i = 0; i < dataBean.getData().getUser_lst().size(); i++) {
                if (i == 0) {
                    tvGongao.setText(dataBean.getData().getUser_lst().get(i).getUsername());
                } else {
                    tvGongao.setText(tvGongao.getText().toString() + "       " + dataBean.getData().getUser_lst().get(i).getUsername());
                }
            }
        } else {
            tvGongao.setText("暂无用户支付");
        }
        if (dataBean.getData().getLottery_info().getType().equals("2")) {
            tvJoin.setEnabled(false);
            tvJoin.setClickable(false);
            tvJoin.setBackgroundResource(R.drawable.shape_button_checked_false);
            tvJoin.setText("正在开奖");
        }else{
            tvJoin.setEnabled(true);
            tvJoin.setClickable(true);
            tvJoin.setBackgroundResource(R.drawable.shape_button_checked);
            tvJoin.setText("立即圆梦");
        }
        isJoin=dataBean.getData().getLottery_info().getIs_participate().equals("0")?false:true;
    }

    @Override
    public void date(JoinBean dataBean) {
        showJoinSuccessmDialog(dataBean.getData().getOrder().getActive_number());
        isJoin=true;
    }

    @Override
    public void date(OpenRedBean dataBean) {
        if (dataBean.getData().getLq_money().getType().equals("1")) {
            showZhongJiangReslutDialog(dataBean.getData().getLq_money().getMoney());
        } else {
            showZhongJiangYuanMengDialog(dataBean.getData().getLq_money().getMoney());
        }
    }

    private class LuckyNumberAdapter extends BaseQuickAdapter<ChooseMoneyBean, BaseViewHolder> {

        public LuckyNumberAdapter(int layoutResId, @Nullable List<ChooseMoneyBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(final BaseViewHolder helper, ChooseMoneyBean item) {
            ImageView iv_img = helper.getView(R.id.iv_img);
            iv_img.setImageResource(item.getImage());
            ImageView iv_check = helper.getView(R.id.iv_check);
            if (item.isChecked()) {
                iv_check.setImageResource(R.drawable.checked);
            } else {
                iv_check.setImageResource(R.drawable.unchecked);
            }
            helper.addOnClickListener(R.id.iv_check);
            TextView TextStatistics = helper.getView(R.id.Text_Statistics);
            TextStatistics.setText(item.getStatistics() + "人已选");
        }
    }

    @OnClick({R.id.iv_mine, R.id.tv_join, R.id.tv_join_count, R.id.tv_perfect_info, R.id.tv_share_dream, R.id.tv_myrecord, R.id.tv_lookall, R.id.tv_look_problem, R.id.iv_weixin, R.id.iv_friendcirlce, R.id.iv_qq, R.id.iv_qq_zone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_mine:
                LoginHelper.login(this, new LoginHelper.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        startActivity(new Intent(mContext, MineActivity.class));
                    }
                });
                break;
            case R.id.tv_join:
                LoginHelper.login(this, new LoginHelper.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        if (isJoin){
                            Toast.makeText(mContext, "您已参加本期圆梦", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        presenter.data((String) CacheUtils.get("token"), Issue);
                    }
                });
                break;
            case R.id.tv_join_count:
                Intent intent = new Intent(this, JoinRecordActivity.class);
                intent.putExtra("issue", Issue);
                startActivity(intent);
                break;
            case R.id.tv_perfect_info:
                LoginHelper.login(this, new LoginHelper.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        Intent intent = new Intent(mContext, MyDreamActivity.class);
                        startActivity(intent);
                    }
                });
                break;
            case R.id.tv_share_dream:
                LoginHelper.login(this, new LoginHelper.LoginCallBack() {
                    @Override
                    public void onLogin() {

                    }
                });
                break;
            case R.id.tv_myrecord:
                LoginHelper.login(this, new LoginHelper.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        startActivity(new Intent(mContext, MyRecordActivity.class));
                    }
                });
                break;
            case R.id.tv_lookall:
                startActivity(new Intent(mContext, LookAllRecordActivity.class));
                break;
            case R.id.tv_look_problem:
                startActivity(new Intent(mContext, ProblemActivity.class));
                break;
            case R.id.iv_weixin:
                break;
            case R.id.iv_friendcirlce:
                break;
            case R.id.iv_qq:
                break;
            case R.id.iv_qq_zone:
                break;
        }
    }


    @Override
    public void onEventMainThread(int eventCode, final Bundle bundle) {
        super.onEventMainThread(eventCode);
        if (eventCode == EventBusCode.JoinF5) {
            JoinPresenter.data(Issue, (String) CacheUtils.get("token"));
        } else if (eventCode == EventBusCode.MainF5) {
            if (TextUtils.isEmpty((String) CacheUtils.get("token"))) {
                MainPresenter.data("2", "0");
            } else {
                MainPresenter.data("1", (String) CacheUtils.get("token"));
            }
        } else if (eventCode == EventBusCode.MainOpenRed) {
            if (TextUtils.isEmpty((String) CacheUtils.get("token"))) {
                MainPresenter.data("2", "0");
            } else {
                MainPresenter.data("1", (String) CacheUtils.get("token"));
            }
            showOpenRedBaoDialog();
        }
    }


    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() > preTime + 2000) {
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            preTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();//相当于finish()
            removeAllActivitys();//删除所有引用
        }
    }
}
